<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>健康档案管理系统</title>
    <!-- 引入jQuery -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        :root {
            --primary-color: #2c3e50;
            --secondary-color: #3498db;
            --health-color: #e74c3c;
            --normal-color: #2ecc71;
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Segoe UI', '微软雅黑', sans-serif;
        }

        body {
            background: #f5f6fa;
            min-height: 100vh;
        }

        .container {
            max-width: 1200px;
            margin: 2rem auto;
            padding: 0 20px;
        }

        .health-header {
            text-align: center;
            padding: 2rem;
            background: linear-gradient(45deg, var(--primary-color), var(--secondary-color));
            color: white;
            border-radius: 10px;
            margin-bottom: 2rem;
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
        }

        .record-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(350px, 1fr));
            gap: 2rem;
        }

        .health-card {
            background: white;
            border-radius: 15px;
            padding: 1.5rem;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
            position: relative;
            transition: transform 0.3s;
        }

        .health-card:hover {
            transform: translateY(-5px);
        }

        .patient-info {
            display: flex;
            align-items: center;
            margin-bottom: 1.5rem;
        }

        .avatar {
            width: 60px;
            height: 60px;
            border-radius: 50%;
            background: var(--secondary-color);
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 1.2rem;
            margin-right: 1rem;
        }

        .basic-info {
            flex: 1;
        }

        .patient-name {
            font-size: 1.3rem;
            color: var(--primary-color);
            margin-bottom: 0.3rem;
        }

        .health-status {
            display: flex;
            flex-wrap: wrap;
            gap: 1rem;
            margin-bottom: 1.5rem;
        }

        .status-item {
            flex: 1;
            min-width: 120px;
            text-align: center;
            padding: 0.8rem;
            border-radius: 8px;
            background: #f8f9fa;
        }

        .status-label {
            font-size: 0.9rem;
            color: #7f8c8d;
            margin-bottom: 0.5rem;
        }

        .status-value {
            font-size: 1.1rem;
            font-weight: 600;
            color: var(--primary-color);
        }

        .medical-info {
            border-top: 2px solid #eee;
            padding-top: 1.5rem;
        }

        .doctor-info {
            display: flex;
            align-items: center;
            margin-top: 1rem;
            padding: 1rem;
            background: #f8f9fa;
            border-radius: 8px;
        }

        .badge {
            padding: 0.3rem 0.8rem;
            border-radius: 20px;
            font-size: 0.85rem;
            display: inline-block;
        }

        .normal {
            background: var(--normal-color);
            color: white;
        }

        .abnormal {
            background: var(--health-color);
            color: white;
        }

        .icon {
            width: 30px;
            text-align: center;
            margin-right: 1rem;
            color: var(--secondary-color);
        }

        .container { max-width: 1200px; margin: 0 auto; padding: 20px; }
        .health-header { text-align: center; margin-bottom: 30px; }
        .record-grid { display: grid; gap: 20px; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); }
        .health-card { background: #fff; border-radius: 10px; padding: 20px; box-shadow: 0 2px 8px rgba(0,0,0,0.1); }
        .patient-info { display: flex; align-items: center; margin-bottom: 15px; }
        .avatar {
            width: 40px; height: 40px;
            background: #4CAF50; color: white;
            border-radius: 50%; display: flex;
            align-items: center; justify-content: center;
            margin-right: 15px;
        }
        .status-item { margin: 8px 0; }
        .status-label { color: #666; font-size: 0.9em; }
        .status-value { font-weight: 500; }
        .badge {
            padding: 2px 8px;
            border-radius: 12px;
            font-size: 0.8em;
            margin-left: 8px;
        }
        .normal { background: #e8f5e9; color: #2e7d32; }
        .abnormal { background: #ffebee; color: #c62828; }
        .error-message {
            padding: 20px;
            background: #ffebee;
            border-radius: 8px;
            text-align: center;
            color: #c62828;
        }
        .retry-btn {
            margin-top: 10px;
            padding: 6px 16px;
            background: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
    </style>
</head>

<body>
<div class="container">
    <div class="health-header">
        <h1>家庭成员健康档案</h1>
        <p id="update-time">数据加载中...</p>
    </div>

    <div class="record-grid" id="healthRecords">
        <!-- 动态内容将插入到这里 -->
    </div>
</div>

<script>
    $(document).ready(function() {
        // Cookie处理函数
        function getCookie(name) {
            return document.cookie.match('(^|;)\\s*' + name + '\\s*=\\s*([^;]+)')?.pop() || null;
        }

        // 主数据加载函数
        function loadHealthData() {
            const username = decodeURIComponent(getCookie('username') || '');
            const token = decodeURIComponent(getCookie('token') || '');
            if (!username) {
                showError('请先登录系统');
                return;
            }

            $.ajax({
                url: `http://localhost:8000/user/archive/get/archiveOfUser/${encodeURIComponent(username)}`,
                type: 'GET',
                dataType: 'json',
                headers: {
                    'Authorization': `${token}`
                },
                xhrFields: { withCredentials: true },
                success: function(response) {
                    console.log('完整响应:', response);

                    if (response.code === 200) {
                        if (response.data && response.data.length > 0) {
                            renderHealthData(response.data);
                            updateTime();
                        } else {
                            showError('没有找到健康档案记录');
                        }
                    } else {
                        showError(`请求失败：${response.message || '未知错误'}`);
                    }
                },
                error: function(xhr) {
                    document.cookie = 'token=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;';
                    window.location.href = 'http://localhost:5173';
                    showError(`请求失败：${xhr.statusText}`);
                }
            });
        }

        // 数据渲染函数
        function renderHealthData(records) {
            const $container = $('#healthRecords').empty();

            records.forEach(record => {
                const $card = $('<div>').addClass('health-card');

                // 患者基本信息
                $card.append(
                    $('<div>').addClass('patient-info').append(
                        $('<div>').addClass('avatar').text(record.name?.charAt(0) || '?'),
                        $('<div>').addClass('basic-info').append(
                            $('<h2>').addClass('patient-name').text(record.name || '未命名用户'),
                            $('<div>').addClass('health-status').append(
                                createStatusItem('年龄', record.age ? `${record.age} 岁` : '未记录'),
                                createStatusItem('性别', parseGender(record.gender))
                            )
                        )
                    )
                );

                // 健康指标信息
                const $medicalInfo = $('<div>').addClass('medical-info');
                $medicalInfo.append(
                    createHealthItem('血糖', record.sugar, 'mmol/L'),
                    createHealthItem('血压', record.pressure, 'mmHg'),
                    createStatusItem('身高体重',
                        [record.height, record.weight]
                            .filter(Boolean)
                            .join('cm / ') + 'kg'),
                    createVisionItem(record.vision),
                    createDoctorInfo(record.doctorName,record.result)
                );

                $card.append($medicalInfo);
                $container.append($card);
            });
        }

        // 通用状态项创建
        function createStatusItem(label, value) {
            return $('<div>').addClass('status-item').html(`
            <div class="status-label">${label}</div>
            <div class="status-value">${value || '未检测'}</div>
        `);
        }

        // 健康指标项创建
        function createHealthItem(label, value, unit) {
            const status = checkHealthStatus(label, value);
            return $('<div>').addClass('status-item').html(`
            <div class="status-label">${label}</div>
            <div class="status-value">
                ${formatValue(value) || '--'}
                ${unit ? `<span class="unit">${unit}</span>` : ''}
                ${status ? `<span class="badge ${status}">${status === 'normal' ? '正常' : '异常'}</span>` : ''}
            </div>
        `);
        }

        // 医生信息
        function createDoctorInfo(doctorName,result) {
            return $('<div>').addClass('doctor-info').html(`
<!--            <i class="fas fa-user-md"></i>-->
            <div>
                <div class="status-label">诊断医生</div>
                <div class="status-value">${doctorName || '未指定'}</div><br>
                <div class="status-label">诊断结果</div>
                <div class="status-value">${result || '未提交'}</div>
            </div>
        `);
        }

        // 视力特殊处理
        function createVisionItem(value) {
            return createHealthItem('视力', formatVision(value), '');
        }

        // 健康状态检查
        function checkHealthStatus(label, value) {
            if (!value) return null;

            // 血糖正常范围：3.9 ~ 6.1 mmol/L
            if (label === '血糖') {
                const num = parseFloat(value);
                return (num >= 3.9 && num <= 6.1) ? 'normal' : 'abnormal';
            }

            // 血压正常范围：<140/90 mmHg
            if (label === '血压') {
                const [systolic, diastolic] = value.split('/').map(Number);
                console.log(systolic, diastolic);
                return ( (90 < systolic && systolic < 140) && (60 < diastolic && diastolic < 90) ) ? 'normal' : 'abnormal';
            }

            return null;
        }

        // 数据格式化
        function formatValue(value) {
            if (!value) return null;
            // 移除可能存在的多余空格
            return value.toString().trim();
        }

        // 视力格式化（例如：1.0/0.8）
        function formatVision(value) {
            if (!value) return null;
            return value.split('/')
                .map(v => parseFloat(v).toFixed(1))
                .join('/');
        }

        // 性别解析
        function parseGender(gender) {
            const mappings = { male: '男', female: '女' };
            return gender ? (mappings[gender.toLowerCase()] || gender) : '未知';
        }

        // 错误处理
        function showError(message) {
            $('#healthRecords').html(`
            <div class="error-message">
                ⚠️ ${message}
                <button class="retry-btn">重新加载</button>
            </div>
        `).find('.retry-btn').click(loadHealthData);
        }

        // 更新时间显示
        function updateTime() {
            $('#update-time').text(`最后更新：${new Date().toLocaleString()}`);
        }

        // 初始化加载
        loadHealthData();
    });
</script>
</body>

</html>
